package com.jkkc.lib.base.util

import android.graphics.Bitmap
import android.graphics.Canvas
import android.view.ViewGroup
import com.blankj.utilcode.util.ToastUtils
import java.io.File
import java.io.FileOutputStream

/**
 * Author:LiXian
 *
 *
 * Desc:view转img
 * Version:1.0
 * date 2023/2/8 13:31
 */
object View2ImageUtil {

    fun view2Image(view: ViewGroup, path: String?, name: String) {
        val bitmap = getBitmapByView(view)
        val fos: FileOutputStream
        val imagePath: String
        try {
            // SD卡根目录
            val file = File(path, "$name.png")
            if (file.exists()) {
                file.delete()
            }
            fos = FileOutputStream(file)
            imagePath = file.absolutePath
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos)
            fos.flush()
            fos.close()
        } catch (e: Exception) {
            e.printStackTrace()
            ToastUtils.showShort("保存失败")
            return
        }
        view.destroyDrawingCache()
        ToastUtils.showShort("保存成功$imagePath")
    }

    private fun getBitmapByView(layout: ViewGroup): Bitmap {
        val bitmap = Bitmap.createBitmap(layout.width, layout.height, Bitmap.Config.RGB_565)
        val canvas = Canvas(bitmap)
        layout.draw(canvas)
        return bitmap
    }
}